<template>
  <page-lr>
      <el-form size="small" :model="searchForm" label-width="90px" slot="content-right">
        <el-form-item label="污染指标：">
          <el-button v-for="(item,index) in legend.list" :key="index" size="small" :type="legend.type == item.name ? 'primary' : 'default'" @click="changeType(item.name)">
            {{ item.name }}
          </el-button>
        </el-form-item>
        <el-form-item label="统计类型：">
          <!-- <el-radio-group v-model="initData.type" @change="changeDateType" class="m-r-10">
            <el-radio-button v-for="(item,index) in initData.dateList" :key="index" :label="item.id" >{{item.name}}</el-radio-button>
          </el-radio-group> -->
          <el-button v-for="(item,index) in initData.dateList" :key="index" size="small" :type="initData.type == item.id ? 'primary' : 'default'" @click="changeDateType(item.id)">
            {{ item.name }}
          </el-button>
          <my-dateRange v-if="initData.type == 'custom'" :start.sync="initData.start_date" :end.sync="initData.end_date" @change="getList" style="width:100%;" />
          <el-date-picker v-if="initData.type == 'day'" v-model="initData.day" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" @change="changeDate"></el-date-picker>
          <el-date-picker v-if="initData.type == 'month'" v-model="initData.month" type="month" value-format="yyyy-MM" placeholder="选择月份" @change="changeDate"></el-date-picker>
          <el-date-picker v-if="initData.type == 'year'" v-model="initData.year" type="year" value-format="yyyy" placeholder="选择年份" @change="changeDate"></el-date-picker>
        </el-form-item>
      </el-form>
    <template slot="content-left">
      <v-chart :options="option" autoresize style="height:400px;width:100%"></v-chart>
      <v-chart :options="prevOption" autoresize style="height:400px;width:100%"></v-chart>
    </template>
  </page-lr>
</template>
<script>
import {city} from '@/config/env';
export default {
  data() {
    return {
      searchForm:{
        start_date: '2023-01-01',
        end_date: '2023-05-18',
      },
      dateValue:{

      },
      initData:{
        type: 'day',
        day: null,
        month: null,
        year: null,
        start_date: null,
        end_date: null,
        dateList:[
          {id: 'day', name:'日'},
          {id: 'month', name:'月'},
          {id: 'year', name:'年'},
          {id: 'custom', name:'自定义'},
        ]
      },
      typeList:[
        {id:1,name: '优', value: 0, },
        {id:2,name: '良', value: 0, },
        {id:3,name: '轻度污染', value: 0, },
        {id:4,name: '中度污染', value: 0, },
        {id:5,name: '重度污染', value: 0, },
        {id:6,name: '严重污染', value: 0, },
      ],
      legend:{
        type: 'PM₂.₅',
        typeId: 'pm25',
        index: 0,
        list:[
          // {id: 'aqi', name: 'AQI', values: [0,50,100,150,200,300]},
          {id: 'pm25', name: 'PM₂.₅', values: [0,35,75,115,150,250]},
          {id: 'pm10', name: 'PM₁₀', values: [0,50,150,250,350,420]},
          {id: 'so2', name: 'SO₂', values: [0,50,150,475,800,1600]},
          {id: 'no2', name: 'NO₂', values: [0,40,80,180,280,565]},
          {id: 'co', name: 'CO', values: [0,2,4,35,14,24]},
          {id: 'o3_8h', name: 'O₃_8h', values: [0,100,160,215,265,800]},
        ],
        typeList:[],
      },
      list:{
        current: [],
        prev: [],
      },
      option: {},
      prevOption: {}
    }
  },
  created() {
    this.initData.day = this.$moment().add(-1, 'd').format('YYYY-MM-DD');
    this.initData.month = this.$moment().format('YYYY-MM');
    this.initData.year = this.$moment().format('YYYY');
    this.initData.start_date = this.$moment().add(-8, 'd').format('YYYY-MM-DD');
    this.initData.end_date = this.$moment().add(-1, 'd').format('YYYY-MM-DD');
    this.changeDateType('day');
  },
  methods: {
    changeType(val){
      this.legend.type = val;
      this.legend.typeList = JSON.parse(JSON.stringify(this.typeList));
      let i,list;
      this.legend.list.forEach((item,index) => {
        if(item.name == val){
          i = index;
          this.legend.index = index;
          this.legend.typeId = item.id;
          list = item.values;
        }
      });
      this.legend.typeList = this.legend.typeList.map((item, index) => {
        item.value = list[index];
        return item;
      });
      this.initOptions();
      this.initPrevOptions();
    },
    changeDateType(val){
      this.initData.type = val;
      this.getList();
    },
    getNowParams(){
      let params = {
        start_date: null,
        end_date: null
      };
      switch(this.initData.type){
        case 'day':
          params.start_date = this.initData.day;
          params.end_date = this.initData.day;
          break;
        case 'month':
          params.start_date= this.$moment(this.initData.month).startOf('months').format('YYYY-MM-DD');
          params.end_date =this.$moment(this.initData.month).endOf('months').format('YYYY-MM-DD');
          break;
        case 'year':
          params.start_date = this.$moment(this.initData.year).startOf('year').format('YYYY-MM-DD');
          params.end_date = this.$moment(this.initData.year).endOf('year').format('YYYY-MM-DD');
          break;
        case 'custom':
          params.start_date = this.initData.start_date;
          params.end_date = this.initData.end_date;
          break;
      };
      return params;
    },
    getLastParams(){
      let params = {
        start_date: '',
        end_date: ''
      };
      switch(this.initData.type){
        case 'day':
          let date = new Date(this.initData.day).setFullYear(new Date(this.initData.day).getFullYear() - 1);
          params.start_date = this.$moment(date).format('YYYY-MM-DD');
          params.end_date = this.$moment(date).format('YYYY-MM-DD');
          break;
        case 'month':
          const str = this.$moment(this.initData.month).format('YYYY-MM-DD');
          let month = new Date(str).setFullYear(new Date(str).getFullYear() - 1);
          params.start_date = this.$moment(month).startOf('months').format('YYYY-MM-DD');
          params.end_date = this.$moment(month).endOf('months').format('YYYY-MM-DD');
          break;
        case 'year':
          const year = Number(this.initData.year);
          params.start_date = `${year-1}-01-01`;
          params.end_date = `${year-1}-12-31`;
          break;
        case 'custom':
          const date0 = new Date(this.initData.start_date).setFullYear(new Date(this.initData.start_date).getFullYear() - 1);
          const date1 = new Date(this.initData.end_date).setFullYear(new Date(this.initData.end_date).getFullYear() - 1);
          params.start_date = this.$moment(date0).format('YYYY-MM-DD');
          params.end_date = this.$moment(date1).format('YYYY-MM-DD');
          break;
      }
      return params;
    },
    changeDate(val){
      this.getList();
    },
    async getList(){
      this.list.current = await this.$request('get', '/aqi/stations_compare', this.getNowParams());
      this.list.prev = await this.$request('get', '/aqi/stations_compare', this.getLastParams());
      this.initOptions();
      this.initPrevOptions();
    },
    initOptions() {
      let current = [];
      let prev = [];
      for (const d of this.list.current) {
        if (d.position_name === city) {
          current.unshift(
            {
              name: d.position_name,
              value: d[this.legend.typeId]
            },
            {
              name: '',
              value: null
            }
          );
        } else {
          current.push({
            name: d.position_name,
            value: d[this.legend.typeId]
          });
        }        
      }

      for (const d of this.list.prev) {
        if (d.position_name === city) {
          prev.unshift(
            {
              name: d.position_name,
              value: d[this.legend.typeId]
            },
            {
              name: '',
              value: null
            }
          );
        } else {
          prev.push({
            name: d.position_name,
            value: d[this.legend.typeId]
          })
        };
      }

      const unit = this.legend.typeId === 'co' ? 'mg/m³' : 'μg/m³';
      this.option = {
        color: ['#9E87FF', '#58D5FF'],
        title: {
          text: `${this.legend.type}浓度对比`,
          left: 'center',
          top: 15,
          textStyle: {
            fontFamily: 'AlibabaPuHuiTi-Bold',
            color: '#000',
            fontSize: 24,
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: (params) => {
            if (!params[0].name) {
              return;
            }
            return `分析对象<span class="ms-4 ps-2">${params[0].name}</span>` + 
            `<div>${params[1].marker}${params[1].seriesName} <span class="ms-3">${params[1].value} ${unit}</span></div>` + 
            `<div>${params[0].marker}${params[0].seriesName} <span class="ms-3">${params[0].value} ${unit}</span></div>`;
          }
        },
        grid: {
          top: 60,
          left: 80,
          right: 20,
          bottom: 50,
        },
        legend: {
          top: 30,
          right: 40,
          textStyle: {
            fontSize: 16,
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000'
          }
        },
        xAxis: {
          type: 'category',
          data: current.map(i => i.name),
          axisLabel: {
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 15,
          }
        },
        yAxis: {
          type: 'value',
          name: unit,
          nameLocation: 'middle',
          nameGap: 50,
          nameTextStyle: {
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 18,
          },
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 15,
          }
        },
        series: [
          {
            name: '上年同期',
            type: 'bar',
            barMaxWidth: 35,
            data: prev
          },
          {
            name: '分析日期',
            type: 'bar',
            barMaxWidth: 35,
            data: current
          }
        ]
      }
      console.log(this.option);
    },
    initPrevOptions(){
      const data = [];
      const name0 = this.list.current.map(i => i.position_name);
      const name1 = this.list.prev.map(i => i.position_name);
      const name = Array.from(new Set(name0.concat(name1)));
      for (const n of name) {
        const citem = this.list.current.find(i => i.position_name === n);
        const c = citem ? Number((citem)[this.legend.typeId]) : 0;
        const pitem = this.list.prev.find(i => i.position_name === n);
        const p = pitem ? Number((pitem)[this.legend.typeId]) : 0;
        const v = p === 0 ? 100 : +((c - p) / p * 100).toFixed(2);
        if (n === city) {
          data.unshift(
            {
              name: n,
              value: v,
              itemStyle: {
                color: v < 0 ? '#22ca29' : '#f43d03'
              }
            },
            {
              name: '',
              value: null,
            }
          );
        } else {
          data.push({
            name: n,
            value: v,
            itemStyle: {
              color: v < 0 ? '#22ca29' : '#f43d03'
            }
          });
        }
      }
      this.prevOption = {
        title: {
          text: `${this.legend.type}浓度变化率`,
          left: 'center',
          top: 25,
          textStyle: {
            fontFamily: 'AlibabaPuHuiTi-Bold',
            color: '#000',
            fontSize: 24,
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          },
          formatter: (params) => {
            if (!params[0].name) {
              return;
            }
            return `分析对象<span class="ms-4 ps-2">${params[0].name}</span>` + 
            `<div>${params[0].marker}浓度变化 <span class="ms-3" style="color: ${params[0].color}">${params[0].value} %</span></div>`;
          }
        },
        grid: {
          top: 80,
          left: 80,
          right: 20,
          bottom: 50,
        },
        xAxis: {
          type: 'category',
          data: data.map(i => i.name),
          boundaryGap: true,
          splitLine:{
            show: false,
          },
          axisLine:{
            onZero: false
          },
          axisLabel: {
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 15,
          }
        },
        yAxis: {
          min: -100,
          max: 100,
          type: 'value',
          axisLabel: {
            fontFamily: 'AlibabaPuHuiTi-Regular',
            color: '#000',
            fontSize: 15,
            formatter: (val) => {return val + '%'}
          }
        },
        series: [{
          name: '浓度变化率',
          type: 'bar',
          data: data,
          barMaxWidth: 50,
          label: {
            show: false,
            position: 'top',
            distance: 0,
            fontSize: 14,
            offset: [0, -10],
          },
        }]
      };
    }
  }
}
</script>